package cn.dai.SocketProgramming;

import org.junit.Test;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author ArkD42
 * @file 1 - Java基础语法
 * @create 2020 - 04 - 22 - 19:47
 */
public class TCP_Test {
    @Test // 服务端
    public void server() throws Exception {
        // 创建服务器程序
        ServerSocket server = new ServerSocket(65000);

        Socket client = server.accept(); // 表示接受进来的客户端套接字

        InputStream inputStream = client.getInputStream();

        byte[] bytesBuffer = new byte[512];

        int len;

        while ((len = inputStream.read(bytesBuffer)) != -1){
            String str = new String(bytesBuffer,0,len);
            System.out.println(str);
        }

        System.out.println("来自服务器的消息：已收到客户端：" + client.getInetAddress().getHostAddress() + " 的消息");

        // 关闭资源
        inputStream.close();
        client.close();
        server.close();
    }

    @Test // 客户端
    public void client() throws Exception {

        // 这是要连接对方的socket信息,IP + port
        Socket client = new Socket(InetAddress.getByName("localhost"),65000);

        OutputStream outputStream = client.getOutputStream();
        outputStream.write("来自客户端发送的消息: Connect Success!!!".getBytes());

        // 流对象释放
        outputStream.close();

        // 套接字释放
        client.close();
    }
}
